package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author kabuda
 * @create 2022-09-03 14:58
 */
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //ant路径匹配器，可以识别通配符
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获得本次请求的uri
        String uri = request.getRequestURI();

        //定义不需要拦截的请求路径(backend/**页面可以访问但是没有请求获得数据)
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //2.判断本次请求是否需要处理
        boolean check = check(urls, uri);
        //3.如果不需要请求，则直接放行
        if (check) {
            log.info("该请求不需要拦截：{}", uri);
            filterChain.doFilter(request, response);
            return;
        }

        //4.1判断登录状态，如果已经登录，则直接放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("已登录，id为{}", request.getSession().getAttribute("employee"));
            //在ThreadLocal
            BaseContext.set((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        //4.2判断登录状态，如果已经登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("已登录，id为{}", request.getSession().getAttribute("user"));
            //在ThreadLocal
            BaseContext.set((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        //5.如果未登录，则返回错误信息给前端（前端判断了，如果返回NOTLOGIN则跳转到登录页面）
        //过滤器方式返回是void，不是R所以不能直接返回，我们使用response返回一个流传递信息
        log.info("未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }




    //匹配需要处理路径方法
    public boolean check(String[] urls, String uri) {
        for (String url : urls) {
            boolean match = ANT_PATH_MATCHER.match(url, uri);
            if (match) {
                //需要处理
                return true;
            }
        }
        //不需要处理
        return false;
    }
}
